package com.mz.ozy.activity.home;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.hintview.ColorPointHintView;
import com.mz.ozy.R;
import com.mz.ozy.WpkApp;
import com.mz.ozy.activity.shop.ScheduledOrderActivity;
import com.mz.ozy.activity.shop.ScheduledOrderActivity1;
import com.mz.ozy.adapter.ScheduledAdapter;
import com.mz.ozy.adapter.ScheduledBannerAdapter;
import com.mz.ozy.adapter.SortListAdapter;
import com.mz.ozy.base.BaseActivity;
import com.mz.ozy.bean.DbBean;
import com.mz.ozy.bean.EventBean;
import com.mz.ozy.bean.NetBean;
import com.mz.ozy.bean.ScheduledOrderBean;
import com.mz.ozy.bean.SortBean;
import com.mz.ozy.constants.Constants;
import com.mz.ozy.mvp.presenter.ScheduledPresenter;
import com.mz.ozy.mvp.view.ScheduledContract;
import com.mz.ozy.utils.LocationHelper;
import com.mz.ozy.utils.ToastUtils;
import com.mz.ozy.utils.Utils;
import com.yanzhenjie.permission.AndPermission;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author lifeStyle on 2020/5/7 0007.
 */
public class ScheduledDeliveryActivity extends BaseActivity<ScheduledContract.View, ScheduledPresenter> implements ScheduledContract.View {
    @BindView(R.id.rl_private_content)
    RelativeLayout mRlPrivateContent;
    @BindView(R.id.rl_private_relocation)
    RelativeLayout mRlReLocation;
    @BindView(R.id.tv_relocation_msg)
    TextView mTvRelocationMsg;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_home_city)
    TextView tvHomeCity;
    @BindView(R.id.rollPagerView)
    RollPagerView rollPagerView;
    @BindView(R.id.iv_bannerPager)
    ImageView ivBannerPager;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.recyclerView2)
    RecyclerView mRecyclerView2;       //热门分类
    @BindView(R.id.tv_real_payment)
    TextView mTvRealPayment;
    @BindView(R.id.tv_real_num)
    TextView mTvRealNum;
    @BindView(R.id.right)
    TextView mRightTextView;
    private SortListAdapter mAdapter;
    private ScheduledAdapter mHotDoorSortAdapter;
    private ScheduledBannerAdapter mBannerAdapter;
    private List<SortBean.ClassificationBean> mClassificationBeans = new ArrayList<>();
    private List<SortBean.ClassBListBean> mListBeans = new ArrayList<>();
    private List<SortBean.ImgBannerBean> mBannerListBeans = new ArrayList<>();
    private String carid;
    private SortBean.ClassBListBean editBean;
    private int totalNum = 0;
    private double totalPrice = 0.00;
    private double totalMarketPrice = 0.00;
    private boolean isFirstLoad = false;
    private boolean reLocation = true;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scheduled);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        tvHomeCity.setText(LocationHelper.getCity());
        final String title = getIntent().getStringExtra("title");
        tvTitle.setText(title);
        initLocationState();
        initView();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventBean event) {
        //刷新购物车
        if (event.getCode() == Constants.EventCode.SCHEDULED_ORDER_SUCCESS) {
            totalNum = 0;
            totalPrice = 0.00;
            totalMarketPrice = 0.00;
            mTvRealNum.setText("共0件 合计:");
            mTvRealPayment.setText("¥0.00");
            if (mPresenter != null) {
                mPresenter.geAssetsInfo(this, LocationHelper.getCity(), LocationHelper.getmAddress(), carid, false);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void initView() {
        rollPagerView.setAnimationDurtion(500);
        rollPagerView.setHintView(new ColorPointHintView(this, Color.WHITE, getResources().getColor(R.color.c_80ffffff)));
        mBannerAdapter = new ScheduledBannerAdapter(this, mBannerListBeans);
        rollPagerView.setAdapter(mBannerAdapter);
        mAdapter = new SortListAdapter(this, mClassificationBeans);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setAdapter(mAdapter);

        mHotDoorSortAdapter = new ScheduledAdapter(mListBeans);
        mHotDoorSortAdapter.setHasStableIds(true);
        LinearLayoutManager layoutManager1 = new LinearLayoutManager(this);
        layoutManager1.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView2.setLayoutManager(layoutManager1);
        mRecyclerView2.setHasFixedSize(true);
        mRecyclerView2.setAdapter(mHotDoorSortAdapter);

        mHotDoorSortAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                editBean = mHotDoorSortAdapter.getItem(position);
                switch (view.getId()) {
                    case R.id.rl_item_view:
                        Intent intent = new Intent(ScheduledDeliveryActivity.this, ScheduledDetailActivity.class);
                        intent.putExtra("goodsId", editBean.getId() + "");
                        intent.putExtra("attribute", editBean.getWeight());
                        startActivity(intent);
                        break;
                    case R.id.iv_add:
                        editBean.setNum(editBean.getNum() + 1);
                        mPresenter.operateGoods(ScheduledDeliveryActivity.this, String.valueOf(editBean.getId()), editBean.getGid(), editBean.getNum() + "", "1");
                        break;
                    case R.id.iv_minus:
                        if (editBean.getNum() < 1) {
                            ToastUtils.showToast("商品数不能小于0");
                            return;
                        }
                        editBean.setNum(editBean.getNum() - 1);
                        mPresenter.operateGoods(ScheduledDeliveryActivity.this, String.valueOf(editBean.getId()), editBean.getGid(), editBean.getNum() + "", "2");
                        break;
                }
            }
        });
        mRightTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(ScheduledDeliveryActivity.this, DeliveryListActivity.class));
            }
        });
    }

    private void reLocationPrivate() {
        AndPermission.with(this).permission(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)

                .onGranted(permissions -> {
                    LocationHelper.setOnLocationListener(new LocationHelper.onLocationListener() {
                        @Override
                        public void locationSuccess() {
                            initLocationState();
                        }
                    });
                    reLocation = true;
                    LocationHelper.initLocationOption();
                })
                .onDenied(permissions -> {
                    ToastUtils.showToast("为了功能正常使用，请您开启定位与存储权限");
                })
                .start();
    }

    @OnClick({R.id.image_back, R.id.tv_home_city, R.id.btn_submit, R.id.tv_relocation})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_relocation:
                reLocationPrivate();
                break;
            case R.id.image_back:
                finish();
                break;
            case R.id.btn_submit:
                if (totalNum != 0) {
                    mPresenter.onBuy(this);
                } else {
                    ToastUtils.showToast("请先选择要购买的商品");
                }
                break;
            case R.id.tv_home_city:
//                Intent intent = new Intent(this, CitySelectActivity.class);
//                startActivityForResult(intent, 101);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101 && resultCode == 101) {
            DbBean dbBean = (DbBean) data.getSerializableExtra("dbbean");
            tvHomeCity.setText(dbBean.getAreaName());
        }
    }

    public void updateSortData(int position, SortBean.ClassificationBean classificationBean) {
        if (classificationBean.getId() != 0) {
            carid = classificationBean.getId() + "";
        } else {
            carid = "";
        }
        mPresenter.geAssetsInfo(this, LocationHelper.getCity(), LocationHelper.getmAddress(), carid, false);
    }

    @Override
    public void handleFailResponse(NetBean bean) {
        if ("1078".equals(bean.getRespCode())) {
            Toast.makeText(this, bean.getRespMsg(), Toast.LENGTH_SHORT).show();
            mTvRelocationMsg.setText("当前所在地区未开通");
            mRlReLocation.setVisibility(View.VISIBLE);
            mRlPrivateContent.setVisibility(View.GONE);
        } else {
            super.handleFailResponse(bean);
        }
    }

    private void initLocationState() {
        if (LocationHelper.isIsLocate()) {
            if (TextUtils.isEmpty(LocationHelper.getCity())) {
                tvHomeCity.setText("未知");
            } else {
                tvHomeCity.setText(LocationHelper.getCity());
            }
            if (reLocation) {
                if (mPresenter != null) {
                    mPresenter.geAssetsInfo(ScheduledDeliveryActivity.this, LocationHelper.getCity(), LocationHelper.getmAddress(), "", true);
                }
                reLocation = false;
            }
        } else {
            mTvRelocationMsg.setText("定位不到您的所在位置，请确认定位功能正常");
            mRlReLocation.setVisibility(View.VISIBLE);
            mRlPrivateContent.setVisibility(View.GONE);
        }
    }

    @Override
    public void geAssetsInfoSuccess(SortBean sortBean) {
        if (sortBean != null) {
            mRlReLocation.setVisibility(View.GONE);
            mRlPrivateContent.setVisibility(View.VISIBLE);
            mBannerListBeans.clear();
            final List<SortBean.ImgBannerBean> bannerList = sortBean.getImg_list();
            if (bannerList != null && bannerList.size() > 0) {
                for (SortBean.ImgBannerBean bannerListBean : bannerList) {
                    mBannerListBeans.add(bannerListBean);
                }
            } else {
                rollPagerView.setVisibility(View.GONE);
                ivBannerPager.setVisibility(View.VISIBLE);
            }
            mBannerAdapter.notifyDataSetChanged();
            if (mBannerListBeans.size() == 1) {
                rollPagerView.setHintView(null);
            }
            mClassificationBeans.clear();
            if (sortBean.getClass_list().size() > 0) {
                mClassificationBeans.add(new SortBean.ClassificationBean("推荐"));
            }
            mClassificationBeans.addAll(sortBean.getClass_list());
            mAdapter.notifyDataSetChanged();
            mListBeans.clear();
            mListBeans.addAll(sortBean.getProduct_list());
            mHotDoorSortAdapter.notifyDataSetChanged();
            if (!isFirstLoad) {
                isFirstLoad = true;
                totalNum = sortBean.getZnum();
                totalPrice = Double.parseDouble(sortBean.getZje());
                totalMarketPrice = Double.parseDouble(sortBean.getZjf());
                mTvRealNum.setText("共" + totalNum + "件 合计:");
                mTvRealPayment.setText(getPrice());
            }
        }
    }

    private String getPrice() {
        String price = "";
        if (totalPrice != 0.00) {
            price += "¥";
            price += Utils.subTwoNumber(totalPrice);
        }
        if (totalMarketPrice != 0.00) {
            if (!TextUtils.isEmpty(price)) {
                price += "+";
                price += Utils.subTwoNumber(totalMarketPrice);
                price += "积分";
            } else {
                price += Utils.subTwoNumber(totalMarketPrice);
                price += "积分";
            }
        }
        if (TextUtils.isEmpty(price)) {
            price = "¥0.00";
        }
        return price;
    }

    public void caculatePrice(boolean check) {
        if (check) {
            totalNum = totalNum + 1;
            double curPrice = 0.00;
            double curMarketPrice = 0.00;
            if (!TextUtils.isEmpty(editBean.getPrice())) {
                curPrice = Double.parseDouble(editBean.getPrice());
            }
            if (!TextUtils.isEmpty(editBean.getMarket_price())) {
                curMarketPrice = Double.parseDouble(editBean.getMarket_price());
            }
            totalPrice = totalPrice + curPrice;
            totalMarketPrice = totalMarketPrice + curMarketPrice;
        } else {
            totalNum = totalNum - 1;
            double curPrice = 0.00;
            double curMarketPrice = 0.00;
            if (!TextUtils.isEmpty(editBean.getPrice())) {
                curPrice = Double.parseDouble(editBean.getPrice());
            }
            if (!TextUtils.isEmpty(editBean.getMarket_price())) {
                curMarketPrice = Double.parseDouble(editBean.getMarket_price());
            }
            totalPrice = totalPrice - curPrice;
            totalMarketPrice = totalMarketPrice - curMarketPrice;
        }
        mTvRealNum.setText("共" + totalNum + "件 合计:");
        mTvRealPayment.setText(getPrice());
    }

    @Override
    public void onEditGoodsCountSuccess(String type) {
        if ("1".equals(type)) {
            caculatePrice(true);
        } else if ("2".equals(type)) {
            caculatePrice(false);
        }
        mHotDoorSortAdapter.notifyDataSetChanged();
    }

    @Override
    public void onBuySuccess(ScheduledOrderBean orderBean) {
        ScheduledOrderActivity1.start(this, orderBean);
    }
}
